package com.yc.sole.framework.context;


import com.alibaba.ttl.TransmittableThreadLocal;
import com.yc.sole.framework.web.BaseUserInfo;

import java.util.Objects;

/**
 * 当前用户线程工具类
 *
 * @author yizuomin
 * @date 2022/1/17 23:08
 **/
public class SecureContextHolder {

    private static final TransmittableThreadLocal<BaseUserInfo> USER_INFO_THREAD_LOCAL = new TransmittableThreadLocal<>();

    /**
     * @param userInfo set
     */
    public static void setUserInfo(BaseUserInfo userInfo) {
        USER_INFO_THREAD_LOCAL.set(userInfo);
    }

    /**
     * @return get
     */
    public static BaseUserInfo getUserInfo() {
        BaseUserInfo userInfo = USER_INFO_THREAD_LOCAL.get();
        if (Objects.nonNull(userInfo)) {
            return userInfo;
        }
        return null;
    }

    /**
     * @return 获取用户id
     */
    public static Long getUserId() {
        BaseUserInfo userInfo = USER_INFO_THREAD_LOCAL.get();
        if (Objects.nonNull(userInfo)) {
            return userInfo.getId();
        }
        return null;
    }

    /**
     * @return 获取用户名
     */
    public static String getUsername() {
        BaseUserInfo userInfo = USER_INFO_THREAD_LOCAL.get();
        if (Objects.nonNull(userInfo)) {
            return userInfo.getUsername();
        }
        return null;
    }

    /**
     * 清空
     */
    public static void removeUser() {
        if (Objects.nonNull(USER_INFO_THREAD_LOCAL.get())) {
            USER_INFO_THREAD_LOCAL.remove();
        }
    }
}
